<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchaseOrderProcessSub;
use App\Models\Purchase\PurchasePayOrderApprove;
use App\Models\Purchase\PurchasePreSettleOrder;
use App\Models\Purchase\PurchaseSettleOrder;
use App\Services\Balance\Balance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * 采购订单执行情况相关
 */
class PurchaseOrderProcessController extends BaseController
{
    /**
     * 获取列表
     */
    public function getorderlist(Request $request)
    {
        $isgetall = $request->isgetall ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchaseOrderProcess::getList($request, $cpid, $manger_id, $isgetall);
        /***
         * 获取“供应商余额”列表，实付金额，来源于 采购订单付款数据，order_list，字段名 order_list_pay_money
         *
         * 给前端直接返回 $order_list_pay_money  单位：元，前端没时间修改，后端处理；2025.05.23
         *
        */
        if($list['list']){
            foreach ($list['list'] as $key => $item) {
                $order_list_pay_money = 0;
                $order_list = PurchasePayOrderApprove::where(['cpid' =>$item['cpid'],'manger_id'=>$item['manger_id']])
                    ->whereRaw('FIND_IN_SET(?,order_ids)',$item['order_id'])->select(['id','order_list'])->get();
                foreach ($order_list as $orderItem) {
                    $order_list_info = json_decode($orderItem['order_list'],true);
                    foreach ($order_list_info as $infoItem) {
                        if($infoItem['id'] == $item['order_id']){
                            $order_list_pay_money += $infoItem['pay_money'];
                        }
                    }
                }
                $list['list'][$key]['order_list_pay_money'] = mathfuncmoney('div',$order_list_pay_money,100,2);
            }
        }
//        $mangerlist = Manger::where([
//            'cpid' => $cpid,
//            'status' => 1
//        ])->where(function ($query) {
//            $query->WhereRaw('FIND_IN_SET(?,utypes)', [2])
//                ->orWhereRaw('FIND_IN_SET(?,utypes)', [3])
//                ->orWhereRaw('FIND_IN_SET(?,utypes)', [4])
//                ->orWhereRaw('FIND_IN_SET(?,utypes)', [6])
//                ->orWhereRaw('FIND_IN_SET(?,utypes)', [7]);
//        })->get();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
    /**
     * 获取详情
     */
    public function getorderinfo(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4) {
            $info = PurchaseOrderProcess::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        } else {
            $info = PurchaseOrderProcess::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        }

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info]]);
    }
    /**
     * 采购订单完成，多退少补--哪种情况可以完结
     * 后结算可以根据预结算单进行完结，也可以根据结算单完结
     * 其他模式均需要根据结算单完结
     * @return void
     */
    public function dofinish(Request $request)
    {
        $id = $request->id ?? 0;
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseOrderProcess::where(['id' => $id,  'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if ($info->is_finish != 1) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可重复操作']);
        }


        if ($info->is_sync != 2) {
            return response()->json(['code' => '001', 'msg' => '未同步结算单，不可操作']);
        }



        //判断是否可以完结
        // $settleorder = PurchaseSettleOrder::where(['cpid' => $cpid, 'order_id' => $info->order_id])->first();
        // if ($info->settle_model == 3) { //后结算
        //     if (!$settleorder) { //根据预结算单完结


        //         $presettleorder = PurchasePreSettleOrder::with('suborder')->where(['cpid' => $cpid,  'is_del' => 1, 'order_id' => $order_id, 'settle_status' => 1, 'settle_model' => 3])
        //             ->get()->toArray();
        //         if (count($presettleorder) <= 0) {
        //             return response()->json(['code' => '001', 'msg' => '预结算单不存在，不可完结']);
        //         }

        //         //根据预结算单进行完结逻辑






        //     }
        // } else {
        //     if (!$settleorder) {
        //         return response()->json(['code' => '001', 'msg' => '无结算单，不可完结']);
        //     }
        // }





        if ($info->settle_model == 3) { //后结算
            $presettleorder = PurchasePreSettleOrder::with('suborder')->where(['cpid' => $cpid,  'is_del' => 1, 'order_id' => $order_id, 'settle_status' => 1, 'settle_model' => 3])
                ->get()->toArray();
            if (count($presettleorder) <= 0) {
                return response()->json(['code' => '001', 'msg' => '预结算单不存在，不可完结']);
            }
        }

        DB::beginTransaction();
        try {
            Balance::purchaseSettleRecharge($info->custom_id, $cpid, $info->taxamount_total, $this->mangerinfo['id']);


            //更新结算单完结

            //更改库存数据

            //更改供应商余额相关
            $update_data = [
                'is_finish' => 2,
                'finished_at' => time()
            ];
            $info = PurchaseOrderProcess::where(['id' => $id,  'cpid' => $cpid, 'is_del' => 1])->update($update_data);

            DB::commit();
        } catch (\Exception $e) {

            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 点价操作---废弃、平台无需点价
     */
    public function doorderclickprice(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        //点价操作财务进行
        if ($this->mangerinfo['utype'] != 4) {
            // return response()->json(['code' => '001', 'msg' => '无权限']);
        }
        $info = PurchaseOrderProcess::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $info = $info->toArray();
        if ($info['settle_model'] != 2) {
            return response()->json(['code' => '001', 'msg' => '点价模式方可点价']);
        }
        if ($info['is_click'] != 1) {
            return response()->json(['code' => '001', 'msg' => '已点价无法重复点价']);
        }
        //获取子订单的价格
        $sub_order = is_array($request->sub_order) ? $request->sub_order : (is_array(json_decode($request->sub_order, true)) ? json_decode($request->sub_order, true) : []);

        if (count($sub_order) > 0 && count($sub_order) == count($info['suborder'])) {
            $update_sub_order = [];
            $warehousing_money = 0;
            foreach ($sub_order as $val) {
                $val = is_array($val) ? $val : (is_array(json_decode($val, true)) ? json_decode($val, true) : []);
                if (!isset($val['sub_order_id']) || $val['sub_order_id'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '无效参数！']);
                }

                if (!isset($val['price']) || $val['price'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '无效参数！!']);
                }

                $sub_order_info = PurchaseOrderProcessSub::where([['process_order_id', $order_id], ['cpid', $cpid], ['sub_order_id', $val['sub_order_id']]])->first();
                if (!$sub_order_info) {
                    return response()->json(['code' => '001', 'msg' => '子订单不存在']);
                }
                $sub_order_info = $sub_order_info->toArray();
                $update_sub_order_item = ['price' => $val['price'], 'sub_order_id' => $val['sub_order_id']];
                //更改入库订单金额
                $update_sub_order_item['warehousing_money'] = mathfuncmoney('mul', mathfuncweight('div', $sub_order_info['warehousing_weight'], 1000, 4), $update_sub_order_item['price']);
                $update_sub_order[] = $update_sub_order_item;

                $warehousing_money = mathfuncmoney('add', $warehousing_money, $update_sub_order_item['warehousing_money']);
            }
        } else {
            //获取未生成的子订单
            return response()->json(['code' => '001', 'msg' => '子订单参数错误']);
        }

        DB::beginTransaction();
        try {

            foreach ($update_sub_order as $key => $val) {
                PurchaseOrderProcessSub::where([['process_order_id', $order_id], ['cpid', $cpid], ['sub_order_id', $val['sub_order_id']]])->update($val);
            }
            PurchaseOrderProcess::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])
                ->update(['click_at' => time(), 'is_click' => 2, 'warehousing_money' => $warehousing_money]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '订单点价失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '订单点价成功']);
    }
}
